package com.jiayuge.mail;

import com.jiayuge.server.pojo.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * 功能: 消息接收者
 *
 * @Program: yeb
 * @Date: 2021-11-30 18:37
 * @Author Jiayu.Yang
 */
@Component
public class MailReceiver {

    //创建日志工具，方便打印
    private static final Logger LOGGER = LoggerFactory.getLogger(MailReceiver.class);

    //邮件发送
    @Autowired
    private   JavaMailSender javaMailSender;
    //邮件配置
    @Autowired
    private  MailProperties mailProperties;
    //模板引擎
    @Autowired
    private  TemplateEngine templateEngine;

    //邮件监听
    @RabbitListener(queues = "mail.welcome")
    public void handler(Employee employee) {
        //创建消息
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg);
        try {
            //发件人
            helper.setFrom(mailProperties.getUsername());
            //收件人
            helper.setTo(employee.getEmail());
            //邮件主题
            helper.setSubject("入职欢迎邮件");
            //发送日期
            helper.setSentDate(new Date());

            //邮件内容
            Context context = new Context();
            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());
            //将数据导入模板
            String mail = templateEngine.process("mail", context);
            //设置发送文本
            helper.setText(mail,true);
            //发送
            javaMailSender.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }


}
